import React, { useState, useRef } from 'react';
import {
  StyleSheet,
  TouchableOpacity,
  ScrollView,
  Animated,
  Dimensions,
  Alert,
  Platform,
} from 'react-native';
import { Text, View } from '@/components/Themed';
import { FontAwesome } from '@expo/vector-icons';
import Colors from '@/constants/Colors';

// 模拟题目数据接口
interface Question {
  id: number;
  type: 'single' | 'multiple' | 'judge';
  content: string;
  options: string[];
  answer: string | string[];
}

// 模拟题目数据
const mockQuestions: Question[] = [
  {
    id: 1,
    type: 'single',
    content: '以下哪个是JavaScript的基本数据类型？',
    options: ['Array', 'Object', 'String', 'Function'],
    answer: 'String',
  },
  {
    id: 2,
    type: 'multiple',
    content: '以下哪些是React的特点？',
    options: ['组件化', '虚拟DOM', '单向数据流', '双向绑定'],
    answer: ['组件化', '虚拟DOM', '单向数据流'],
  },
  {
    id: 3,
    type: 'judge',
    content: 'React Native可以同时开发iOS和Android应用。',
    options: ['正确', '错误'],
    answer: '正确',
  },
];

export default function ExamScreen() {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [answers, setAnswers] = useState<{[key: number]: string | string[]}>({});
  const scrollViewRef = useRef<ScrollView>(null);
  const fadeAnim = useRef(new Animated.Value(1)).current;

  const handleAnswer = (questionId: number, answer: string) => {
    const question = mockQuestions[currentIndex];
    let newAnswer: string | string[];

    if (question.type === 'multiple') {
      const currentAnswers = answers[questionId] as string[] || [];
      if (currentAnswers.includes(answer)) {
        newAnswer = currentAnswers.filter(a => a !== answer);
      } else {
        newAnswer = [...currentAnswers, answer];
      }
    } else {
      newAnswer = answer;
    }

    setAnswers(prev => ({
      ...prev,
      [questionId]: newAnswer,
    }));

    // 单选题和判断题自动跳转到下一题
    if (question.type !== 'multiple' && currentIndex < mockQuestions.length - 1) {
      setTimeout(() => handleNext(), 500);
    }
  };

  const handleNext = () => {
    if (currentIndex < mockQuestions.length - 1) {
      Animated.sequence([
        Animated.timing(fadeAnim, {
          toValue: 0,
          duration: 200,
          useNativeDriver: true,
        }),
        Animated.timing(fadeAnim, {
          toValue: 1,
          duration: 200,
          useNativeDriver: true,
        }),
      ]).start();

      setCurrentIndex(prev => prev + 1);
    } else {
      Alert.alert('提示', '已经是最后一题了');
    }
  };

  const handlePrevious = () => {
    if (currentIndex > 0) {
      Animated.sequence([
        Animated.timing(fadeAnim, {
          toValue: 0,
          duration: 200,
          useNativeDriver: true,
        }),
        Animated.timing(fadeAnim, {
          toValue: 1,
          duration: 200,
          useNativeDriver: true,
        }),
      ]).start();

      setCurrentIndex(prev => prev - 1);
    }
  };

  const renderQuestion = () => {
    const question = mockQuestions[currentIndex];
    const selectedAnswers = answers[question.id] || (question.type === 'multiple' ? [] : '');

    return (
      <Animated.View style={[styles.questionContainer, { opacity: fadeAnim }]}>
        <View style={styles.questionHeader}>
          <Text style={styles.questionType}>
            {question.type === 'single' && '单选题'}
            {question.type === 'multiple' && '多选题'}
            {question.type === 'judge' && '判断题'}
          </Text>
          <Text style={styles.progress}>
            {currentIndex + 1} / {mockQuestions.length}
          </Text>
        </View>

        <Text style={styles.questionContent}>{question.content}</Text>

        <View style={styles.optionsContainer}>
          {question.options.map((option, index) => (
            <TouchableOpacity
              key={index}
              style={[
                styles.optionButton,
                Array.isArray(selectedAnswers)
                  ? selectedAnswers.includes(option) && styles.selectedOption
                  : selectedAnswers === option && styles.selectedOption,
              ]}
              onPress={() => handleAnswer(question.id, option)}
            >
              <Text style={[
                styles.optionText,
                Array.isArray(selectedAnswers)
                  ? selectedAnswers.includes(option) && styles.selectedOptionText
                  : selectedAnswers === option && styles.selectedOptionText,
              ]}>
                {String.fromCharCode(65 + index)}. {option}
              </Text>
            </TouchableOpacity>
          ))}
        </View>
      </Animated.View>
    );
  };

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.title}>模拟考试</Text>
        <View style={styles.timer}>
          <FontAwesome name="clock-o" size={20} color={Colors.light.tint} />
          <Text style={styles.timerText}>45:00</Text>
        </View>
      </View>

      <ScrollView
        ref={scrollViewRef}
        style={styles.scrollView}
        contentContainerStyle={styles.scrollViewContent}
        showsVerticalScrollIndicator={false}
      >
        {renderQuestion()}
      </ScrollView>

      <View style={styles.footer}>
        <TouchableOpacity
          style={[styles.navButton, currentIndex === 0 && styles.disabledButton]}
          onPress={handlePrevious}
          disabled={currentIndex === 0}
        >
          <Text style={styles.navButtonText}>上一题</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[styles.navButton, currentIndex === mockQuestions.length - 1 && styles.disabledButton]}
          onPress={handleNext}
          disabled={currentIndex === mockQuestions.length - 1}
        >
          <Text style={styles.navButtonText}>下一题</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 16,
    backgroundColor: '#fff',
    ...Platform.select({
      ios: {
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.1,
        shadowRadius: 4,
      },
      android: {
        elevation: 4,
      },
    }),
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
  },
  timer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  timerText: {
    marginLeft: 8,
    fontSize: 16,
    color: Colors.light.tint,
  },
  scrollView: {
    flex: 1,
  },
  scrollViewContent: {
    padding: 16,
  },
  questionContainer: {
    backgroundColor: '#fff',
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
    ...Platform.select({
      ios: {
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.1,
        shadowRadius: 4,
      },
      android: {
        elevation: 2,
      },
    }),
  },
  questionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 16,
  },
  questionType: {
    fontSize: 14,
    color: Colors.light.tint,
    fontWeight: '500',
  },
  progress: {
    fontSize: 14,
    color: '#666',
  },
  questionContent: {
    fontSize: 16,
    lineHeight: 24,
    marginBottom: 20,
  },
  optionsContainer: {
    gap: 12,
  },
  optionButton: {
    padding: 12,
    borderRadius: 8,
    backgroundColor: '#f8f8f8',
    borderWidth: 1,
    borderColor: '#eee',
  },
  selectedOption: {
    backgroundColor: Colors.light.tint,
    borderColor: Colors.light.tint,
  },
  optionText: {
    fontSize: 16,
    color: '#333',
  },
  selectedOptionText: {
    color: '#fff',
  },
  footer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    padding: 16,
    backgroundColor: '#fff',
    ...Platform.select({
      ios: {
        shadowColor: '#000',
        shadowOffset: { width: 0, height: -2 },
        shadowOpacity: 0.1,
        shadowRadius: 4,
      },
      android: {
        elevation: 4,
      },
    }),
  },
  navButton: {
    paddingVertical: 12,
    paddingHorizontal: 24,
    borderRadius: 8,
    backgroundColor: Colors.light.tint,
  },
  navButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '500',
  },
  disabledButton: {
    backgroundColor: '#ccc',
  },
});